//
//  YCLComposeViewController.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/19.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class YCLComposeViewController: UIViewController {
    
    // 照片选择view是否显示
    private var isShowPhotoSelectorView = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        setupNavigationBar()
        
        //设置ui
        //必须设为控制器view的第一个子view才能自动偏移
        setupTextView()
        setupPhotoSelectorView()
        setupToolbar()
        setupLengthTipLabel()
        
        
        //注册键盘的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    //
    override func viewDidAppear(animated: Bool) {
        
        if !isShowPhotoSelectorView {
            //一进入就弹出键盘
            textView.becomeFirstResponder()
        }
 
    }
    
    //移除通知
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //键盘frame值改变时调用
    @objc private func willChangeFrame(notifaction: NSNotification) {
    
//        YCLPrint("\(notifaction)")
        //获得键盘的endframe
        let endFrame = notifaction.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let y = -(UIScreen.mainScreen().bounds.height - endFrame.origin.y)
        
        //设置动画时间
        let duration = notifaction.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //更新toolbar底部约束
        toolBar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(y)
        }
        
        //开启动画效果
        UIView.animateWithDuration(duration) { 
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    //MARK:微博文本长度限制文本
    private let statusMaxLength = 140
    
    private func setupLengthTipLabel() {
        
        
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.snp_makeConstraints { (make) in
            
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
            make.trailing.equalTo(view).offset(-4)
        }
        
        //设置内容
        lengthTipLabel.text = "\(statusMaxLength)"
    }
    
    //MARK: 发微博的文本view
    private func setupTextView() {
    
        //添加子控件
        view.addSubview(textView)
        
        textView.delegate = self
        
//        textView.backgroundColor = UIColor.cyanColor()
        //添加约束
        textView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(view)
            
        }
        
    }
    
    //MARK: 底部的工具条
    private func setupToolbar() {
    
        //添加子控件
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        //创建toolBar上的item
        var items = [UIBarButtonItem]()
        
        //每个item对应的图片名称
        let itemSettings =
        [
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_add_background","action": "add"]
        ]
        
        //设置每个item的内容
        for dict in itemSettings {
            
            let item = UIBarButtonItem.init(imageName: dict["imageName"]!, target: self, action: Selector(dict["action"]!))
            
            items.append(item)
            
            //添加弹簧
            items.append(UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        //移除最后一根弹簧
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    //MARK: 照片选择器
    private func setupPhotoSelectorView () {
    
        let photoSelectorView = photoSelectorVC.view
        
        //添加子控件
        view.addSubview(photoSelectorView)
        
        self.addChildViewController(photoSelectorVC)
        
        //设置约束
        // 添加约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.height * 0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height * 0.6)
        }
        
    }
    
    //按钮点击事件
    //点击图片按钮
    @objc private func picture() {
//        print("图片")
        isShowPhotoSelectorView = true
        //更新约束
        photoSelectorVC.view.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(self.view)
        }
        
        UIView.animateWithDuration(0.5) { 
            
            //重新布局
            self.view.layoutIfNeeded()
        }
        
        //退出键盘
        textView.resignFirstResponder()
        
    }
    
    @objc private func trend() {
        print("#")
    }
    
    
    @objc private func mention() {
        print("@")
    }
    
    //点击表情按钮
    @objc private func emoticon(button: UIButton) {
        
        //退出键盘
        textView.resignFirstResponder()
//        print("表情")
        //如果是系统键盘就弹出表情键盘，如果是表情键盘就弹出系统键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        var normalImg:UIImage?
        var highlightedImg:UIImage?
        
        if textView.inputView == nil {
        
            normalImg = UIImage.init(named: "compose_emoticonbutton_background")
            highlightedImg = UIImage.init(named: "compose_emoticonbutton_background_highlighted")
        }else{
        
            normalImg = UIImage.init(named: "compose_keyboardbutton_background")
            highlightedImg = UIImage.init(named: "compose_emoticonbutton_background_highlighted")
        }
        
        button.setImage(normalImg, forState: UIControlState.Normal)
        button.setImage(highlightedImg, forState: UIControlState.Highlighted)
        
        //延迟0.25s将键盘弹出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { 
            
            self.textView.becomeFirstResponder()
        }
        
    }
    
    
    @objc private func add() {
        print("加号")
    }
    
    //MARK: 导航栏左右两边的按钮
    private func setupNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancel"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("send"))
        
        //禁用右侧按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        let pre = "发微博"
        
        //设置中间文字view
        if let name = YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.screen_name {
            
            let title = pre + "\n" + "\(name)"
            
            //创建label
            let label = UILabel()
            label.font = UIFont.systemFontOfSize(YCLStatusNameFontSize)
            label.numberOfLines = 0
            label.textColor = UIColor.blackColor()
            label.textAlignment = NSTextAlignment.Center
            
            let attMString = NSMutableAttributedString.init(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            
            
            
            attMString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attMString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
            
            label.attributedText = attMString
            
            label.sizeToFit()
            
            navigationItem.titleView = label

        }else {
        
            //没有名字
            navigationItem.title = pre
        }
        
    }
    
    //点击了取消按钮
    @objc private func cancel() {
    
//        YCLPrint("点击了取消按钮")
        //退出键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //点击了发送按钮
    @objc private func send() {
    
//        YCLPrint("点击了发送按钮")
        //发布微博
        
        //获取textview的内容
        let status = textView.emoticonText()
        
        //判断内容长度
        if status.characters.count > statusMaxLength {
            //弹出提示框
            SVProgressHUD.showErrorWithStatus("微博内容超过长度")
            
            return
        }
        
        SVProgressHUD.showInfoWithStatus("正在发送微博")
        
        //获得最近一个图片
        let image = photoSelectorVC.photos.first
        
        //发送微博
        YCLStatusViewModel.sharedStatusViewModel.sendStatus(status, image: image){ (error) in
            
            if error != nil {
            
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            
            //发送微博成功
            SVProgressHUD.showSuccessWithStatus("发送微博成功")
            
            //延迟0.5s关闭发微博界面
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(500 * USEC_PER_SEC)), dispatch_get_main_queue(), {
                
                self.cancel()
            })
            
        }
    }
    
    //MARK: 懒加载控件
    
    //懒加载toolbar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //懒加载textView
    private lazy var textView:YCLPlaceHolderTextView = {
    
        let tv = YCLPlaceHolderTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        
        //设置textview有回弹效果
        tv.alwaysBounceVertical = true
        
        //拖动取消键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

        
        return tv
    }()
    
    //懒加载表情键盘
    private lazy var emoticonKeyboard: YCLEmoticonKeyboard = {
    
        let keyboard = YCLEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    
    
    //剩余字数文本
    private lazy var lengthTipLabel: UILabel = {
        
        let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(12)
        
        return label
    }()

    //懒加载照片选择器控制器
    private lazy var photoSelectorVC: YCLPhotoSelectorController = YCLPhotoSelectorController()
}

extension YCLComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //文本内容发生改变时，重新计算可输入的长度
        let text = textView.emoticonText()
        
        let length = statusMaxLength - text.characters.count
        
        lengthTipLabel.text = "\(length)"
        
        //当输入超过设置的最大长度改变字体颜色
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
    }
}
